package com.spc.redis.serializer;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;

import static com.spc.redis.serializer.SerializerUtil.isPrimitiveOrString;

/**
 * gson 序列化方案实现
 *
 * @author alex
 * @version v1.0 2021/3/17
 */
public class GsonSerializer extends AbstractSerializer {

    public static final String TYPE = "gson";

    private static final Gson GSON = new GsonBuilder().create();

    /**
     * 序列化一个对象到 字符串
     *
     * @param obj
     * @return
     * @throws SerializeException
     */
    @Override
    public <T> String serialize(T obj) throws SerializeException {
        if (isPrimitiveOrString(obj)) {
            return String.valueOf(obj);
        }
        try {
            return GSON.toJson(obj);
        } catch (Exception e) {
            throw new SerializeException(e.getLocalizedMessage());
        }
    }

    /**
     * 反序列化到对象
     *
     * @param value
     * @param clazz
     * @return
     * @throws SerializeException
     */
    @Override
    public <T> T deserialize(String value, Class<T> clazz) throws SerializeException {
        try {
            if (isPrimitiveOrString(clazz)) {
                return toPrimitiveValue(value, clazz);
            }
            return GSON.fromJson(value, clazz);
        } catch (JsonSyntaxException e) {
            throw new SerializeException(e);
        }
    }
}
